//
//  Gif.swift
//  JKTool
//
//  Created by 姜奎 on 2023/6/1.
//

import Foundation
import ImageIO
//import MobileCoreServices
extension JKTool {
    struct Gif: ParsableCommand {
        static var configuration = CommandConfiguration(
            commandName: "gif",
            _superCommandName: "jktool",
            abstract: "制作gif",
            version: "1.0.0"
        )
        
        @Option(name: .shortAndLong, help: "帧时长，default：0.5s")
        var delay: Double = 0.5
        
        @Option(name: .shortAndLong, help: "导出路径")
        var toPath: String?
        
        @Option(name: .shortAndLong, help: "图片组位置")
        var path: String?

        mutating func run() {
            
            func gif(images:[CGImage], to path:String){
                
                // 生成GIF文件
                let gifProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]]
                let destinationURL = URL(fileURLWithPath: path)
                let destinationGIF = CGImageDestinationCreateWithURL(destinationURL as CFURL, kUTTypeGIF, images.count, nil)!
                let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: delay]]
                for image in images {
                    CGImageDestinationAddImage(destinationGIF, image, frameProperties as CFDictionary?)
                }
                CGImageDestinationSetProperties(destinationGIF, gifProperties as CFDictionary?)
                CGImageDestinationFinalize(destinationGIF)
                
                po(tip: "gif制作完成！(\(path))")
            }
            
            let path = path ?? FileManager.default.currentDirectoryPath
            let toPath = toPath ?? (path + "/gif.gif")
            
            guard let imageURLs = try? FileManager.default.contentsOfDirectory(at: URL(fileURLWithPath: path), includingPropertiesForKeys: nil).sorted(by: {
                return $0.lastPathComponent.localizedStandardCompare($1.lastPathComponent) == .orderedAscending
            }) else { return po(tip: "没找到文件(\(path))",type: .error) }
            
            
            let images:[CGImage] = imageURLs.compactMap { url in
                
               guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil) else {
                   return nil
               }
               
               guard let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil) else {
                   return nil
               }
               
                return image
               
            }
            
            guard !images.isEmpty else { return po(tip: "没找到合适的图片(\(path))",type: .error)  }
            
            gif(images: images, to: toPath)
        }
            
    }
}
